import { useEffect, useState, useCallback, useRef } from 'react';
import { Empty, Modal, Input, Spin, message, Table, Typography } from 'antd';
import { DownOutlined, CloseCircleFilled } from '@ant-design/icons';
import { InbizIcon } from '@inbiz/utils';
import Pagination from '@inbiz/basic/Pagination';
import { TextWidget, getMessage } from '@inbiz/react';
import useDebounce from './hook';
import { getGroupList, getGroupPageList } from './service';
import styles from './index.less';

const { Paragraph } = Typography;

const EnvironmentSelect = (props: any) => {
  // model显示控制
  const [visible, $visible] = useState<boolean>(false);
  // 当前选中分组
  const [activeGroup, $activeGroup] = useState('');
  // 当前选中环境变量
  const [activePage, $activePage] = useState<any>(null);
  // 当前选中环境变量名
  const [activePageName, $activePageName] = useState('');
  // 当前选中环境变量详情
  const [activeInfo, $activeInfo] = useState<any>(null);
  // 组列表数据
  const [groupList, $groupList] = useState<any[]>([]);
  // 环境变量列表数据
  const [dataSource, $dataSource] = useState<any[]>([]);
  // 环境变量总数
  const [pageTotal, $pageTotal] = useState<number>(0);
  // 组列表加载
  const [groupLoading, $groupLoading] = useState<boolean>(false);
  // 环境变量列表加载
  const [pageLoading, $pageLoading] = useState<boolean>(true);
  // 当前页码
  const [current, $current] = useState<number>(1);
  // 当前分页数值
  const [pageSize, $pageSize] = useState<number>(10);
  // 分组数据获取状态（是否成功）
  const [loadGroup, $loadGroup] = useState<boolean>(false);
  // 搜索值
  const [searchIpts, $searchIpts] = useState<string>('');
  // 防抖后的搜索值
  const searchTxt = useDebounce(searchIpts, 500);
  // 表格字段配置
  const [listColumns] = useState<any[]>([
    {
      title: getMessage('EnvironmentSelect.variable_nane'), // 变量名
      dataIndex: 'Name',
      key: 'Name',
      width: 178,
      render: (txt: any) => <Paragraph ellipsis={true}>{txt}</Paragraph>,
    },
    {
      title: getMessage('EnvironmentSelect.variable_value'), // 变量值
      dataIndex: 'Value',
      key: 'Value',
      width: 170,
      render: (txt: any) => <Paragraph ellipsis={true}>{txt}</Paragraph>,
    },
    {
      title: getMessage('EnvironmentSelect.remark'), // 备注
      dataIndex: 'Remark',
      key: 'Remark',
      width: 170,
      render: (txt: any) => <Paragraph ellipsis={true}>{txt}</Paragraph>,
    },
  ]);
  // 组件最外层div的dom
  const selectRef: any = useRef();

  // 初始化获取分组列表
  useEffect(() => {
    if (visible) {
      selectRef.current?.focus();
      $groupLoading(true);
      getGroupList()
        .then((res) => {
          if (Array.isArray(res)) {
            $groupList(res);
            if (res.length) {
              $activeGroup(res[0].OutId);
            }
            $loadGroup(true);
          }
          $groupLoading(false);
        })
        .catch(() => {
          $groupLoading(false);
          $pageLoading(false);
        });
    }
  }, [visible]);

  // 组变化获取环境变量列表数据
  useEffect(() => {
    $current(1);
    if (searchTxt === '') {
      if (!loadGroup || activeGroup === '') {
        return;
      }
      $pageLoading(true);
      const page = {
        skipCount: 0,
        maxResultCount: pageSize,
      };
      getGroupPageList(activeGroup, page)
        .then((res) => {
          if (Array.isArray(res.Items)) {
            $dataSource(res.Items);
            $pageTotal(res.TotalCount);
          }
          $pageLoading(false);
        })
        .catch(() => $pageLoading(false));
    } else {
      $searchIpts('');
    }
  }, [activeGroup, loadGroup]);

  // 回填value
  useEffect(() => {
    let value = props.value;
    if (value && value.name && value.value && value.outId && value.key) {
      $activePage(value.outId);
      $activePageName(value.name);
      $activeInfo({
        Value: value.value,
        OutId: value.outId,
        Name: value.name,
        Key: value.key,
      });
    } else {
      $activePageName('');
      $activePage(null);
    }
  }, [props.value]);

  // 防抖后触发搜索
  useEffect(() => {
    $current(1);
    searchPage(searchTxt);
  }, [searchTxt]);

  // 防抖后搜索环境变量
  const searchPage = useCallback(
    (searchTxt: string) => {
      if (!loadGroup || activeGroup === '') {
        return;
      }
      $pageLoading(true);
      const page = {
        skipCount: 0,
        maxResultCount: pageSize,
        SearchText: searchTxt?.trim(),
      };
      getGroupPageList(activeGroup, page)
        .then((res) => {
          if (Array.isArray(res.Items)) {
            $dataSource(res.Items);
            $pageTotal(res.TotalCount);
          }
          $pageLoading(false);
        })
        .catch(() => $pageLoading(false));
    },
    [loadGroup, pageSize, activeGroup],
  );

  // 打开选择弹窗
  const showModal = useCallback(() => {
    if (props.value && props.value.outId) {
      $activePage(props.value.outId);
    }
    $visible(true);
  }, [props.value]);

  // 确定
  const handleOk = useCallback(() => {
    if (activeInfo && activePage) {
      const obj: any = {
        name: activeInfo.Name,
        value: activeInfo.Value,
        outId: activePage,
        key: activeInfo.Key,
      };
      $activePageName(activeInfo.Name);
      props.onChange?.(obj);
      $visible(false);
      $activeGroup('');
      props.onBlur?.();
    } else {
      message.warning(getMessage('EnvironmentSelect.message_no_selected')); // 未选择环境变量
    }
  }, [activePage, activeInfo]);

  // 选中组
  const clickGroup = (id: any) => {
    $activeGroup(id);
  };

  // 选中环境变量
  const clickPage = (item: any) => {
    $activePage(item.OutId);
    $activeInfo(item);
  };

  // 分页器更新值
  const paginationChange = useCallback(
    (e: any) => {
      $current(e.current);
      $pageSize(e.pageSize);
      if (!loadGroup || activeGroup === '') {
        return;
      }
      $pageLoading(true);
      const page = {
        skipCount: (e.current - 1) * e.pageSize,
        maxResultCount: e.pageSize,
        SearchText: searchTxt?.trim(),
      };
      getGroupPageList(activeGroup, page)
        .then((res) => {
          if (Array.isArray(res.Items)) {
            $dataSource(res.Items);
            $pageTotal(res.TotalCount);
          }
          $pageLoading(false);
        })
        .catch(() => $pageLoading(false));
    },
    [searchTxt, activeGroup, loadGroup],
  );

  // 筛选搜索值更新
  const searchChange = (e: any) => {
    $searchIpts(e.target.value);
  };

  // 清除选中
  const clear = (e: any) => {
    e.stopPropagation();
    props.onChange?.({});
  };

  return (
    <div
      ref={selectRef}
      tabIndex={-1}
      className={styles['setter-environment-select']}
      {...props}
      onBlur={() => {
        !visible && props.onBlur?.();
      }}
    >
      <div onClick={showModal}>
        <div className={styles['like-select']}>
          {activePageName && activePageName !== '' ? (
            <span className={styles['like-value']}>{activePageName}</span>
          ) : (
            <span className={styles['like-placeholder']}>
              <TextWidget>
                EnvironmentSelect.placeHolder_please_select
              </TextWidget>{' '}
              {/* 请选择 */}
            </span>
          )}
          {activePageName && activePageName !== '' ? (
            <>
              <DownOutlined
                style={{ color: '#c7c7c7' }}
                className={styles['more-btn']}
              />
              <CloseCircleFilled
                style={{ color: '#c7c7c7' }}
                className={styles['clear-btn']}
                onClick={clear}
              />
            </>
          ) : (
            <DownOutlined style={{ color: '#c7c7c7' }} />
          )}
        </div>
      </div>
      <Modal
        width={800}
        className={styles['setter-environment-select-model']}
        visible={visible}
        getContainer={false}
        bodyStyle={{ height: 488 }}
        title={getMessage('EnvironmentSelect.modal_title')} // 环境变量选择
        okText={getMessage('global.sure')} // 确定
        cancelText={getMessage('global.cancel')} // 取消
        onCancel={() => {
          $visible(false);
          $activeGroup('');
          $activePage(null);
          props.onBlur?.();
        }}
        onOk={handleOk}
      >
        <div className={styles['model-box']}>
          <div className={styles['content']}>
            <div className={styles['left-tree']}>
              <Spin spinning={groupLoading}>
                <div className={styles['left-group-box']}>
                  {groupList.map((item) => (
                    <p
                      key={item.OutId}
                      className={
                        activeGroup === item.OutId
                          ? `${styles['group-item']} ${styles['active']}`
                          : styles['group-item']
                      }
                      onClick={() => clickGroup(item.OutId)}
                    >
                      <span>{item.Name}</span>
                    </p>
                  ))}
                </div>
              </Spin>
            </div>
            <div className={styles['right-nav']}>
              <Spin spinning={pageLoading}>
                <Input
                  value={searchIpts}
                  onChange={searchChange}
                  placeholder={getMessage(
                    'EnvironmentSelect.search_placeholder',
                  )} // 请输入变量名称
                  suffix={
                    <InbizIcon
                      type="icon-ic-sousuo"
                      style={{ color: '#999' }}
                    />
                  }
                />
                <Table
                  columns={listColumns}
                  dataSource={dataSource}
                  rowKey="OutId"
                  rowSelection={{
                    selectedRowKeys: [activePage],
                    type: 'radio',
                    preserveSelectedRowKeys: true,
                    onChange: (selectedRowKeys: any) => {
                      $activePage(selectedRowKeys?.[0] || '');
                    },
                  }}
                  pagination={false}
                  scroll={{ y: 349 }}
                  onRow={(record: any) => {
                    return {
                      onClick: (e) => {
                        e.stopPropagation();
                        clickPage(record);
                      },
                    };
                  }}
                  locale={{
                    emptyText: (
                      <Empty
                        image={
                          pageLoading ? null : Empty.PRESENTED_IMAGE_SIMPLE
                        }
                        description={
                          pageLoading ? null : (
                            <TextWidget>EnvironmentSelect.no_data</TextWidget>
                          )
                        }
                      />
                    ),
                  }}
                />
                <Pagination
                  size="small"
                  options={[10, 20, 30, 40, 50]}
                  total={pageTotal}
                  current={current}
                  pageSize={pageSize}
                  onChange={paginationChange}
                />
              </Spin>
            </div>
          </div>
        </div>
      </Modal>
    </div>
  );
};

export default EnvironmentSelect;
